package com.hollycrm.ahunicom.sheet.business.logic.hibernate;

import org.springframework.orm.hibernate.HibernateTemplate;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;

import com.hollycrm.ahunicom.sheet.AhBeanResource;
import com.hollycrm.ahunicom.sheet.business.BusinessSupportManagerDefine;
import com.hollycrm.ahunicom.sheet.lightweight.SpRefundmentInfo;
import com.hollycrm.springframework.factory.DefaultBeanFactory;
import com.hollycrm.unicom.security.AuthToken;
import com.hollycrm.unicom.sheet.domain.MainSheet;
import com.hollycrm.unicom.sheet.flow.SheetAction;
import com.hollycrm.unicom.sheet.flowsupport.ActionExecuteLogic;
import com.hollycrm.unicom.sheet.flowsupport.DoOperateContext;
import com.hollycrm.unicom.sheet.lightweight.MainSheetInfo;

public class HibernateDeleteSpRefundmentLogic extends HibernateDaoSupport
		implements ActionExecuteLogic {

	public HibernateDeleteSpRefundmentLogic() {
	}

	public void execute(AuthToken authToken, SheetAction action,
			DoOperateContext context) throws Exception {
		HibernateTemplate ht = getHibernateTemplate();
		BusinessSupportManagerDefine bsmDefine = (BusinessSupportManagerDefine) DefaultBeanFactory
				.getBean(AhBeanResource.BUSINESSSUPPORT_MANAGER_DEFINE);
		String spRefundmentNo = (String) context.getInputAttr("spRefundmentNo");
		String mainSheetFlowNO = (String) context.getInputAttr("sheetFlowNO");
		SpRefundmentInfo spRefundmentInfo = bsmDefine
				.getSpRefundmentInfo(spRefundmentNo);
		MainSheetInfo mainSheetInfo = (MainSheet) ht.load(
				com.hollycrm.unicom.sheet.domain.MainSheet.class,
				mainSheetFlowNO);
		int count = updateSpRefundmentCount(ht, mainSheetInfo);
		mainSheetInfo.setSpareContentField4(count + "");

		ht.delete(spRefundmentInfo);
		ht.update(mainSheetInfo);

	}

	private int updateSpRefundmentCount(HibernateTemplate ht,
			MainSheetInfo mainSheetInfo) throws Exception {
		String countStr = mainSheetInfo.getSpareContentField4();
		if (countStr == null || "".equals(countStr)) {
			countStr = "0";
		}
		int count = Integer.valueOf(countStr).intValue();
		count--;

		if (count < 0) {
			count = 0;
		}
		return count;
	}

}
